<?php

/*
 * Librería que contiene la función de creación de una operación para
 * un usuario que se registra a través de un referido.
 */
require_once '../bootstrap.php';
require_once 'entities/User.php';
require_once 'entities/Visit.php';
require_once 'entities/Media.php';
require_once 'entities/Domain.php';
require_once 'entities/ItemDomain.php';
require_once 'entities/Strategy.php';
require_once 'entities/Fare.php';
require_once 'entities/Operation.php';

define("STRATEGY_NEW_USER_BY_REF", 7); //Strategy ID 7 from DB.

function checkReferer($entityManager, $pUser) {
  
  $refCode = $pUser->getUsuReferalId();
  $usuId = $pUser->getUsuId();
  
  // Validar que existe el usuario con ese refcode
  
  //$userRef = $entityManager->getRepository('User')->findOneBy(array('usuReferenceCode' => $refCode));
  $userRef = $entityManager->find('User', $refCode);
  
  if ($userRef != NULL) {
  
    // Validar que no haya entrado ya por esa ip
    $query = $entityManager->createQuery('SELECT COUNT(v.visId) FROM Visit v
                                          WHERE v.visUsuId = :vis_usu_id AND v.visIp = :vis_ip');
    $query->setParameters(array(
        'vis_usu_id' => $userRef->getUsuId(),
        'vis_ip' => $_SERVER['REMOTE_ADDR'],
    ));

    $result = $query->getSingleScalarResult();

    if ($result == 0) {
      $visit = new Visit();

      $visit->setVisUsuId($userRef->getUsuId());
      //$visit->setVisIp( $_SERVER['REMOTE_ADDR'] );
      $visit->setVisIp(rand(0, 255) . "." . rand(0, 255) . "." . rand(0, 255) . "." . rand(0, 255));
      $visit->setVisAuditDate(time());
      if (isset($_SERVER['HTTP_REFERER'])) {
        $visit->setVisUrlFrom($_SERVER['HTTP_REFERER']);
      } else {
        $visit->setVisUrlFrom("Private");
      }

      $strategy = getActiveStrategy($entityManager, STRATEGY_NEW_USER_BY_REF);

      if ($strategy) {
        $visit->setVisStr($strategy);
      }

      $entityManager->persist($visit);
      $entityManager->flush();
      
      // Si tiene estrategia valido que exista y que este activa
      if (( $strategy ) && ( $strategy->getStrValidityStart() < time() ) && ( $strategy->getStrValidityEnd() > time() )) {
          
        // Obtengo el referal_amount de la estrategia
        $fare = $entityManager->getRepository('Fare')->findOneBy(array('farId' => $strategy->getStrFar()));

        if ($fare !== NULL) {
          
          $status = $entityManager->getRepository('ItemDomain')->findOneBy(array('itdId' => 3));

          $operation = new Operation();

          $operation->setOpeUsu($pUser);
          $operation->setOpeTraId(1567);
          $operation->setOpeType(1); //TODO: ver que hacemos con este campo
          $operation->setOpeStatus($status); // not paid
          $operation->setOpeVis($visit);
          $operation->setOpeReferalAmount($fare->getFarAmount());
          $operation->setOpeStr($strategy);
          $operation->setOpeAuditCreateDate(time());
          $operation->setOpeUsuBeneficiary($userRef);


          $entityManager->persist($operation);
          $entityManager->flush();
          
        }
      }
    }
  }
}

function getActiveStrategy($entityManager, $str) {
   // Obtengo los datos de la estrategia
   $strategy = $entityManager->find('Strategy', $str);

   if (( $strategy ) && ( $strategy->getStrValidityStart() < time() ) && ( $strategy->getStrValidityEnd() > time() )) {
      return $strategy;
   } else {
      return false;
   }
}